import { createRouter, createWebHistory } from 'vue-router'
import ToDoPage from '@/page/ToDoPage';
import CountPage from "@/page/CountPage";
import MyPage from "@/page/MyPage";
import EditUserPage from '@/page/EditUserInfoPage';
import LoginPage from '@/page/LoginPage';
import RegisterPage from '@/page/RegisterPage';
import NotFoundPage from '@/page/NotFoundPage.vue';

const routes = [
    {
        path: '/',
        name: 'todo_page',
        component: ToDoPage,
        meta: {requestAuth: true}
    },
    {
        path: '/count',
        name: 'count_page',
        component: CountPage,
        meta: {requestAuth: true}
    },
    {
        path: '/my',
        name: 'my_page',
        component: MyPage,
        meta: {requestAuth: true}
    },
    {
        path: '/user/edit',
        name: 'edit_user_page',
        component: EditUserPage,
        meta: {requestAuth: true}
    },
    {
        path: '/login',
        name: 'login_page',
        component: LoginPage,
        meta: {requestAuth: false}
    },
    {
        path: '/register',
        name: 'register_page',
        component: RegisterPage,
        meta: {requestAuth: false}
    },
    {
        path: '/404',
        name: '404_page',
        component: NotFoundPage,
        meta: {requestAuth: false}
    },
    {
        path: '/:pathMatch(.*)',
        redirect: '/404',
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    if (to.meta.requestAuth && !localStorage.getItem('jwt_token')) {
        next({name: "login_page"});
    } else {
        next();
    }
})

export default router;
